﻿using System;
using System.Data;

namespace CavemanTools.Sql
{
	internal class SqlServerParamFactory : ParamFactory
	{
		public SqlServerParamFactory(IDbCommand cmd)
			: base(cmd)
		{
			Prefix = "@";
		}

		protected override void MapType(IDbDataParameter param, object value)
		{
			if (value != null)
			{
				var tp = value.GetType();
				if (tp.IsEnum)
				{
					value = Convert.ChangeType(value, tp.BaseType);
				}
				var ct = Type.GetTypeCode(tp);
				if (ct == TypeCode.DateTime)
				{
					var dt = (DateTime) value;
					if (dt < new DateTime(1753, 1, 1))
					{
						param.DbType = DbType.DateTime2;
					}
				}
			}
			if (value==null) value = DBNull.Value;
			param.Value = value;
		}

		public override string FormatParameterName(string name)
		{
			return Prefix + name;
		}
	}
}